package com.lagou.server;

import com.lagou.model.ExamReport;
import com.lagou.model.Question;
import com.lagou.model.User;

import java.io.*;
import java.util.LinkedList;

/**
 * 编程实现数据的存储
 */
public class ServerDao {
    /**
     * 存储学员账户的信息
     */
    private LinkedList<User> userList = new LinkedList<>();

    public void setUserList(LinkedList<User> userList) {
        this.userList = userList;
    }

    public LinkedList<User> getUserList() {
        return userList;
    }

    /**
     * 存储考题信息
     */
    private LinkedList<Question> questions = new LinkedList<>();

    public LinkedList<Question> getQuestions() {
        return questions;
    }

    public void setQuestions(LinkedList<Question> questions) {
        this.questions = questions;
    }

    /**
     * 保存当前正在登陆的账户
     */
    private User currentUser = new User();

    public User getCurrentUser() {
        return currentUser;
    }

    public void clientExamUserName() {
        currentUser.getUserName();
    }

    /**
     * 清空当前用户的信息
     */
    public void clearCurrentUser() {
        currentUser.setUserName(null);
        currentUser.setPassword(null);
    }

    /**
     * 编程实现管理员账号密码的校验并返回
     * @param user
     * @return
     */
    public boolean serverManageCheck(User user) {
        if ("lishufei".equals(user.getUserName()) && "123456".equals(user.getPassword())) {
            //存入当前正在登陆的用户
            currentUser.setUserName(user.getUserName());
            currentUser.setPassword(user.getPassword());
            return true;
        }
        return false;
    }

    /**
     * 校验学员的账号密码
     * @param student
     * @return
     */
    public boolean serverUserCheck(User student) {
        //判断是否存在
        /*for (User u : userList) {
            if (u.getUserName().equals(student.getUserName()) && u.getPassword().equals(student.getPassword())) {
                //存储当前正在登陆的账户
                currentUser.setUserName(student.getUserName());
                currentUser.setPassword(student.getPassword());
                return true;
            }
        }
        return false;*/
        if (userList.contains(student)) {
            //存储当前正在登陆的账户
            currentUser.setUserName(student.getUserName());
            currentUser.setPassword(student.getPassword());
            return true;
        }else {
            return false;
        }
    }

    /**
     * 实现新增学员并返回结果
     * @param student
     * @return
     */
    public boolean serverAddStudent(User student) {
        //判断集合里面是否有和新增的学员重复的    没有元素匹配
        if (userList.stream().noneMatch(user -> user.getUserName().equals(student.getUserName()))) {
            return userList.add(student);
        }else {
            return false;
        }
    }

    /**
     * 实现删除学员并返回结果
     * @param student
     * @return
     */
    public boolean serverDeleteStudent(User student) {
        //遍历集合找到相同的然后删除
        for (User u : userList) {
            if (u.getUserName().equals(student.getUserName())) {
                return userList.remove(u);
            }
        }
        return false;
    }

    /**
     * 实现学员的修改并返回
     * @param student
     * @return
     */
    public boolean serverUpdateStudent(User student) {
        //遍历集合找到相同的然后删除之后再添加新的
        for (User u : userList) {
            if (u.getUserName().equals(student.getUserName())) {
                return userList.remove(u) && userList.add(student);
            }
        }
        return false;
    }

    /**
     * 实现学员的查询并返回
     * @param student
     * @return
     */
    public User serverSearchStudent(User student) {
        //遍历集合找到学员并返回
        for (User u : userList) {
            if (u.getUserName().equals(student.getUserName())) {
                return u;
            }
        }
        return null;
    }

    /**
     * 增加考题
     * @param question
     * @return
     */
    public boolean serverAddQuestion(Question question) {
        return questions.add(question);
    }

    /**
     * 删除考题
     * @param str
     * @return
     */
    public boolean serverDeleteQuestion(String str) {
        //遍历集合看是否包含然后删除
        for (Question q : questions) {
            if (q.getQuestion().contains(str)) {
                return questions.remove(q);
            }
        }
        return false;
    }

    /**
     * 考题修改
     * @param question
     * @param options
     * @param answer
     * @return
     */
    public boolean serverUpdateQuestion(String question, String options, String answer) {
        //遍历集合看是否包含然后删除
        for (Question q : questions) {
            if (q.getQuestion().contains(question)) {
                q.setQuestion(question + options);
                q.setAnswer(answer);
                return true;
            }
        }
        return false;
    }

    /**
     * 查找考题
     * @param str
     * @return
     */
    public Question serverSearchQuestion(String str) {
        //遍历集合看是否包含
        for (Question q : questions) {
            if (q.getQuestion().contains(str)) {
                return q;
            }
        }
        return null;
    }

    /**
     * 导入考题
     * @param q
     * @return
     */
    public boolean serverLoadQuestion(LinkedList<Question> q) {
        return questions.addAll(q);
    }

    /**
     * 修改密码
     * @param newPassword
     * @return
     */
    public boolean serverUpdatePassword(String newPassword) {
        for (User u : userList) {
            if (u.equals(currentUser)) {
                u.setPassword(newPassword);
                currentUser.setPassword(newPassword);
                return true;
            }
        }
        return false;
    }

    /**
     * 保存成绩单到数据库
     * @param examReport
     */
    public void saveExamReportToDataBase(ExamReport examReport) {
        File file = new File("d:/在线考试系统/" + examReport.getUsername());

        ObjectOutputStream oos = null;
        try {
            if (!file.exists()) {
                System.out.println(file.createNewFile() ? "考试成绩单创建成功" : "考试成绩单创建失败");
            }else {
                System.out.println("考试成绩单已存在");
            }
            oos = new ObjectOutputStream(new FileOutputStream(file));

            //写入数据库
            oos.writeObject(examReport);

            //刷新
            oos.flush();
            System.out.println("考试成绩单已经存储到数据库");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //释放资源
            if (null != oos) {
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 从数据库获取当前学员的成绩单
     * @return
     */
    public ExamReport getExamReportToDataBase() {
        File file = new File("d:/在线考试系统/" + getCurrentUser().getUserName());

        if (!file.exists()) {
            return null;
        }
        ObjectInputStream ois = null;
        ExamReport examReport = null;
        try {
            ois = new ObjectInputStream(new FileInputStream(file));
            //读取信息
            examReport = (ExamReport) ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (null != ois) {
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return examReport;
    }

    /**
     * 从本地导入学员信息到集合
     */
    public void loadUserFromDataBase() {
        //从本地文件中读取所有学员信息到List集合中
        File file = new File("d:/在线考试系统/学员信息.txt");

        if (file.exists()) {
            //创建对象输入流
            ObjectInputStream ois = null;
            try {
                ois = new ObjectInputStream(new FileInputStream(file));

                //读取文件
                setUserList((LinkedList<User>) ois.readObject());

                //遍历集合
                if (null == getUserList() || getUserList().isEmpty()) {
                    System.out.println("提示：系统暂无学员信息");
                }else {
                    System.out.println("读取的信息");
                    for (User u : userList) {
                        System.out.println(u);
                    }
                }

            } catch (EOFException e) {
                System.out.println("提示：系统暂无学员信息");
                //e.printStackTrace();
            }catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            } finally {
                //释放资源
                if (null != ois) {
                    try {
                        ois.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }else {
            System.out.println("学员信息存储文件尚未创建");
            System.out.println();
        }
    }

    /**
     * 从本地导入考题信息
     */
    public void loadQuestionsFromDataBase(){
        File file = new File("d:/在线考试系统/考试考题.txt");

        if (file.exists()) {
            //创建对象输入流
            ObjectInputStream ois = null;
            try {
                ois = new ObjectInputStream(new FileInputStream(file));

                //读取文件
                setQuestions((LinkedList<Question>) ois.readObject());

                //遍历集合
                if (null == getQuestions() || getQuestions().isEmpty()) {
                    System.out.println("提示：系统暂无考题！");
                }else {
                    System.out.println("考题如下：");
                    for (Question q : questions) {
                        System.out.println(q);
                    }
                }

            } catch (EOFException e) {
                System.out.println("提示：系统暂无考题！");
                //e.printStackTrace();
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            } finally {
                //释放资源
                if (null != ois) {
                    try {
                        ois.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }else {
            System.out.println("考题信息存储文件尚未创建");
            System.out.println();
        }
    }

    /**
     * 将所有学员信息保存到数据库
     */
    public void saveUserToDataBase() {
        //将学员信息保存到数据库
        File file = new File("d:/在线考试系统/学员信息.txt");
        ObjectOutputStream oos = null;
        try {
            if (!file.exists()) {
                System.out.println(file.createNewFile() ? "学员信息存储文件创建成功" : "学员信息存储文件创建失败");
            }
            oos = new ObjectOutputStream(new FileOutputStream(file));

            //写入数据库
            oos.writeObject(getUserList());

            //刷新
            oos.flush();
            System.out.println("学员信息已经存储到数据库");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //释放资源
            if (null != oos) {
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 将考题保存到数据库
     */
    public void saveQuestionsToDataBase() {
        File file = new File("d:/在线考试系统/考试考题.txt");

        ObjectOutputStream oos = null;
        try {
            if (!file.exists()) {
                System.out.println(file.createNewFile() ? "考题信息存储文件创建成功" : "考题信息存储文件创建失败");
            }
            oos = new ObjectOutputStream(new FileOutputStream(file));
            oos.writeObject(getQuestions());
            oos.flush();
            System.out.println("考题保存成功");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != oos) {
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
